<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CallEmployeeVO } from '#/api/contact/task/call/model';

import { ref } from 'vue';

// import { useAccess } from '@vben/access';
import { useVbenDrawer, useVbenModal } from '@vben/common-ui';
// import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { message, Modal, Popconfirm, Space } from 'ant-design-vue';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  vxeCheckboxCheckedCount,
} from '#/adapter/vxe-table';
import {
  callTaskChangeCallStatus,
  callTaskDataPage,
  callTaskDataRemove,
} from '#/api/contact/task/call';

import importDataModal from './components/import-data-modal.vue';
import { taskDataColumns } from './data';

// const { hasAccessByCodes } = useAccess();
const emit = defineEmits<{ reload: [] }>();
const currTaskId = ref<number | string>();
const taskNameTitle = ref<string>();
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    // trigger: 'row',
  },
  columns: taskDataColumns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await callTaskDataPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          taskId: currTaskId.value,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'call-task-data-list-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  gridOptions,
});

const [BasicDrawer, drawerApi] = useVbenDrawer({
  class: 'w-[80%]',
  onClosed: handleClosed,
  footer: false,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }

    const { taskId, taskName } = drawerApi.getData() as {
      taskId?: number | string;
      taskName?: string;
    };
    currTaskId.value = taskId;
    taskNameTitle.value = taskName;
  },
});

async function handleClosed() {
  currTaskId.value = undefined;
  taskNameTitle.value = '';
}

// 导入人员数据弹窗
const [ImportDataModal, importDataModalApi] = useVbenModal({
  connectedComponent: importDataModal,
});

function handleImport() {
  importDataModalApi.setData({
    taskId: currTaskId.value,
  });
  importDataModalApi.open();
}

async function importSuccess() {
  await tableApi.query();
  emit('reload');
}

async function handleRemove(row: CallEmployeeVO) {
  await callTaskDataRemove([row.id]);
  await tableApi.query();
  emit('reload');
}

function handleMultiRemove() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: CallEmployeeVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await callTaskDataRemove(ids);
      await tableApi.query();
      emit('reload');
    },
  });
}

// 释放呼叫状态
async function handleRelease(row: CallEmployeeVO) {
  row.loading = true;
  await callTaskChangeCallStatus({
    taskId: currTaskId.value,
    employeeId: row.employeeId,
    callStatus: 0,
  });
  message.success('释放成功');
  await tableApi.query();
  row.loading = false;
}
</script>

<template>
  <BasicDrawer :title="`${taskNameTitle} - 呼叫任务数据`">
    <BasicTable>
      <template #table-title>
        <main-title text="人员列表" />
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button
            type="primary"
            v-access:code="['call:employee:add']"
            @click="handleImport"
          >
            导入数据
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['call:employee:remove']"
            @click="handleMultiRemove"
          >
            移除({{ vxeCheckboxCheckedCount(tableApi) }})
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <Popconfirm
            v-if="row.callStatus === 1"
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认释放呼叫锁定状态？"
            @confirm="handleRelease(row)"
          >
            <ghost-button
              v-access:code="['call:employee:changeCallStatus']"
              :loading="row.loading"
              @click.stop=""
            >
              释放
            </ghost-button>
          </Popconfirm>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认移除？"
            @confirm="handleRemove(row)"
          >
            <ghost-button
              danger
              v-access:code="['call:employee:remove']"
              @click.stop=""
            >
              移除
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <ImportDataModal @reload="importSuccess" />
  </BasicDrawer>
</template>
